const jwt = require('jsonwebtoken')

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization?.split(' ')[1]

    if (!token) {
      return res.status(401).json({
        code: 401,
        message: '未提供认证令牌',
        success: false
      })
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-jwt-secret')
    req.user = decoded
    next()
  } catch (err) {
    return res.status(401).json({
      code: 401,
      message: '无效的认证令牌',
      success: false
    })
  }
}
